<template>
  <div class="links-container">
    <!-- 内容区域包装器 -->
    <div class="content-wrapper">
      <!-- 页面头部 -->
      <div class="page-header">
        <h2>我的短链接</h2>
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          创建短链接
        </el-button>
      </div>

      <!-- 链接卡片列表 -->
      <div class="link-grid">
        <el-card 
          v-for="link in linkList" 
          :key="link.id" 
          class="link-card"
        >
          <div class="link-card-header">
            <h3>{{ link.urlTitle }}</h3>
            <el-tag :type="getStatusType(link.status)" size="small">
              {{ getStatusText(link.status) }}
            </el-tag>
          </div>
          <div class="link-card-content">
            <p class="long-url" :title="link.longUrl">{{ link.longUrl }}</p>
            <div class="short-url">
              <el-link type="primary" :href="link.shortUrl" target="_blank">
                {{ link.shortUrl }}
              </el-link>
              <el-button-group>
                <el-button link @click="() => copyUrl(link.shortUrl)">
                  <el-icon><CopyDocument /></el-icon>
                </el-button>
                <el-button link @click="() => showQRCode(link.id)">
                  <el-icon><Share /></el-icon>
                </el-button>
              </el-button-group>
            </div>
            <div class="link-stats">
              <span>访问次数：{{ link.visitCount }}</span>
              <span>创建时间：{{ formatDate(link.createTime) }}</span>
            </div>
          </div>
          <div class="link-card-footer">
            <el-button-group>
              <el-button size="small" type="primary" @click="handleStats(link)">统计</el-button>
              <el-button size="small" type="warning" @click="handleEdit(link)">编辑</el-button>
              <el-button 
                size="small" 
                :type="link.status === 0 ? 'danger' : 'success'"
                @click="handleToggleStatus(link)"
              >
                {{ link.status === 0 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(link)">删除</el-button>
            </el-button-group>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 固定在底部的分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加统计信息对话框 -->
    <el-dialog
      v-model="showStats"
      title="访问统计"
      width="600px"
    >
      <div v-loading="statsLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="总访问次数">{{ stats.visitCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="独立访问次数">{{ stats.uniqueVisitCount || 0 }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 添加编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑短链接"
      width="500px"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <!-- 原始链接（只读） -->
        <el-form-item label="原始链接">
          <el-input v-model="editForm.longUrl" disabled />
        </el-form-item>
        
        <!-- 短链接（只读） -->
        <el-form-item label="短链接">
          <el-input v-model="editForm.shortUrl" disabled />
        </el-form-item>
        
        <!-- 可编辑字段 -->
        <el-form-item label="链接标题" prop="urlTitle">
          <el-input v-model="editForm.urlTitle" placeholder="请输入链接标题" />
        </el-form-item>
        
        <el-form-item label="链接描述" prop="urlDescription">
          <el-input 
            v-model="editForm.urlDescription" 
            type="textarea"
            placeholder="请输入链接描述"
          />
        </el-form-item>
        
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="editForm.expireTime"
            type="datetime"
            placeholder="选择过期时间（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit" :loading="editLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加创建短链接对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建短链接"
      width="500px"
    >
      <el-form :model="linkForm" :rules="rules" ref="linkFormRef" label-width="100px">
        <el-form-item label="原始链接" prop="longUrl">
          <el-input 
            v-model="linkForm.longUrl" 
            placeholder="请输入需要缩短的链接"
          />
        </el-form-item>
        
        <el-form-item label="链接标题" prop="urlTitle">
          <el-input 
            v-model="linkForm.urlTitle" 
            placeholder="请输入链接标题"
          />
        </el-form-item>
        
        <el-form-item label="链接描述" prop="urlDescription">
          <el-input 
            v-model="linkForm.urlDescription" 
            type="textarea"
            placeholder="请输入链接描述"
          />
        </el-form-item>
        
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="linkForm.expireTime"
            type="datetime"
            placeholder="选择过期时间（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleGenerate" :loading="loading">
            生成
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 生成结果展示 -->
    <el-dialog
      v-model="showResult"
      title="短链接生成成功"
      width="500px"
    >
      <div class="result-content">
        <p>您的短链接已生成：</p>
        <el-input
          v-model="fullUrl"
          readonly
        >
          <template #append>
            <el-button @click="() => copyUrl(shortUrl)">复制</el-button>
          </template>
        </el-input>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showResult = false">关闭</el-button>
          <el-button type="primary" @click="handleContinue">
            继续生成
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加二维码对话框 -->
    <el-dialog
      v-model="showQRCodeDialog"
      title="短链接二维码"
      width="360px"
      align-center
    >
      <div class="qrcode-content">
        <img :src="qrcodeUrl" alt="QR Code" v-if="qrcodeUrl" />
        <div v-else class="qrcode-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, CopyDocument, DataLine, Edit, Delete, Share, Loading } from '@element-plus/icons-vue'
import { shortlinkApi } from '../../api/shortlink'

// 创建相关
const showCreateDialog = ref(false)
const linkFormRef = ref(null)
const loading = ref(false)
const linkForm = reactive({
  longUrl: '',
  urlTitle: '',
  urlDescription: '',
  expireTime: ''
})

// 表单验证规则
const rules = {
  longUrl: [
    { required: true, message: '请输入原始链接', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL', trigger: 'blur' }
  ],
  urlTitle: [
    { required: true, message: '请输入链接标题', trigger: 'blur' }
  ]
}

// 生成结果相关
const showResult = ref(false)
const shortUrl = ref('')

// 列表相关
const tableLoading = ref(false)
const linkList = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 状态相关
const showStats = ref(false)
const statsLoading = ref(false)
const stats = ref({})

// 编辑相关
const showEditDialog = ref(false)
const editFormRef = ref(null)
const editLoading = ref(false)
const editForm = reactive({
  id: '',
  urlTitle: '',
  urlDescription: '',
  expireTime: ''
})

// 添加二维码相关的响应式变量
const showQRCodeDialog = ref(false)
const qrcodeUrl = ref('')

// 添加 fullUrl 响应式变量
const fullUrl = ref('')

// 生成短链接
const handleGenerate = async () => {
  if (!linkFormRef.value) return
  
  try {
    await linkFormRef.value.validate()
    loading.value = true
    
    const res = await shortlinkApi.generate(linkForm)
    shortUrl.value = res.data
    
    // 构建完整的URL
    const shortCode = res.data.split('/').slice(-2).join('/')
    const baseUrl = import.meta.env.PROD ? 'http://119.29.101.244' : 'http://localhost:5173'
    fullUrl.value = `${baseUrl}/d/${shortCode}`
    
    showCreateDialog.value = false
    showResult.value = true
    await loadLinkList()
  } catch (error) {
    if (error.response?.data?.code === 40300) {
      // 调用限制错误已经在请求拦截器中处理
      return
    }
    ElMessage.error(error.message || '生成失败')
  } finally {
    loading.value = false
  }
}

// 复制链接
const copyUrl = async (url) => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const domain = userInfo.domain || ''
  const fullUrl = `http://119.29.101.244/d/${domain}/${url}`
  
  try {
    await navigator.clipboard.writeText(fullUrl)
    ElMessage.success('复制成功')
  } catch (error) {
    const input = document.createElement('input')
    input.value = fullUrl
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    ElMessage.success('复制成功')
  }
}

// 继续生成
const handleContinue = () => {
  showResult.value = false
  linkFormRef.value?.resetFields()
}

// 加载链接列表
const loadLinkList = async () => {
  try {
    tableLoading.value = true
    const res = await shortlinkApi.getMyList({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (res.data) {
      linkList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('Load links error:', error)
    ElMessage.error('获取列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadLinkList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadLinkList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadLinkList()
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '正常',
    1: '已失效',
    2: '未发布',
    3: '已删除'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'success',
    1: 'danger',
    2: 'warning',
    3: 'info'
  }
  return typeMap[status] || ''
}

// 切换状态
const handleToggleStatus = async (link) => {
  try {
    const newStatus = link.status === 0 ? 1 : 0
    await shortlinkApi.setStatus(link.id, newStatus)
    ElMessage.success(newStatus === 0 ? '启用成功' : '禁用成功')
    await loadLinkList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 查看统计
const handleStats = async (row) => {
  try {
    statsLoading.value = true
    showStats.value = true
    const res = await shortlinkApi.getStats(row.id)
    stats.value = res.data || {}
  } catch (error) {
    ElMessage.error('获取统计信息失败')
  } finally {
    statsLoading.value = false
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该短链接吗？', '提示', {
      type: 'warning'
    })
    const res = await shortlinkApi.delete(row.id)
    if (res.code === 0) {
      ElMessage.success('删除成功')
      await loadLinkList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 编辑按钮点击
const handleEdit = async (row) => {
  try {
    const res = await shortlinkApi.getInfo(row.id)
    if (res.data) {
      console.log('获取到的数据:', res.data)
      
      // 只回写需要编辑的三个字段
      editForm.id = res.data.id
      editForm.urlTitle = res.data.urlTitle || ''
      editForm.urlDescription = res.data.urlDescription || ''
      editForm.expireTime = res.data.expireTime ? new Date(res.data.expireTime) : ''   
      showEditDialog.value = true
    } else {
      ElMessage.error('获取短链接信息失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取短链接信息失败')
  }
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    await shortlinkApi.update(editForm)
    ElMessage.success('更新成功')
    showEditDialog.value = false
    await loadLinkList()
  } catch (error) {
    ElMessage.error(error.message || '更新失败')
  } finally {
    editLoading.value = false
  }
}

// 显示二维码
const showQRCode = (id) => {
  showQRCodeDialog.value = true
  qrcodeUrl.value = `http://119.29.101.244/api/shortlink/qrcode?id=${id}`
}

onMounted(() => {
  loadLinkList()
})
</script>

<style scoped>
.links-container {
  width: 100%;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  padding-bottom: 60px; /* 为分页组件留出空间 */
}

.content-wrapper {
  flex: 1;
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.link-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.link-card {
  height: 100%;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
}

.link-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
  }
}

.link-card-content {
  .long-url {
    color: #606266;
    margin-bottom: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .short-url {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    
    .el-link {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .el-button-group {
      display: flex;
      gap: 4px;
    }
  }
  
  .link-stats {
    display: flex;
    justify-content: space-between;
    color: #909399;
    font-size: 13px;
  }
}

.link-card-footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.pagination-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 0;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: center;
  z-index: 10;
}

@media screen and (max-width: 768px) {
  .links-container {
    padding: 0 8px;
  }
  
  .link-grid {
    grid-template-columns: 1fr;
  }
}

.qrcode-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.qrcode-content img {
  max-width: 100%;
  height: auto;
}

.qrcode-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #909399;
  
  .el-icon {
    font-size: 24px;
  }
}
</style> 